// src/components/popups/sponsorOverview/scholarshipsByProgram/ScholarshipsByProgramModal.tsx

import type { FC } from 'react';
import { useState, useMemo } from 'react';
import SearchForm from '@/components/popups/sponsorOverview/scholarshipsByProgram/SearchForm';
import ResultTable from '@/components/popups/sponsorOverview/scholarshipsByProgram/ResultTable';
import Pagination from '@/components/sponsorDashboard/mainContent/Pagination';
import { fetchScholarshipsByProgram, type ProgramScholarshipItem } from '@/services/sponsorDashboardService/scholarshipsByProgram';
import type { ScholarshipsByProgramSearchParams } from '@/components/popups/sponsorOverview/scholarshipsByProgram/SearchForm';
import ScholarshipByProgramBarChart from '@/components/popups/sponsorOverview/scholarshipsByProgram/ScholarshipByProgramBarChart';

interface ScholarshipsByProgramProps {
  onClose: () => void;
}

type SortField = 'program_code' | 'program_year' | 'faculty' | 'coop_program' | 'sponsor_count' | 'position' | 'total_amount_per_position' | 'sponsorship_cost' | 'status';
type SortDirection = 'asc' | 'desc';

const ScholarshipsByProgramModal: FC<ScholarshipsByProgramProps> = ({ onClose }) => {
  const [results, setResults] = useState<ProgramScholarshipItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState('');
  const [error, setError] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [sortField, setSortField] = useState<SortField>('program_code');
  const [sortDirection, setSortDirection] = useState<SortDirection>('asc');
  const [showChart, setShowChart] = useState(true);
  const itemsPerPage = 10;

  const sortedResults = useMemo(() => {
    return [...results].sort((a, b) => {
      let aValue: string | number | undefined = a[sortField];
      let bValue: string | number | undefined = b[sortField];

      if (aValue === null || aValue === undefined) aValue = '';
      if (bValue === null || bValue === undefined) bValue = '';

      if (sortField === 'program_year' || sortField === 'position' || sortField === 'sponsor_count' || sortField === 'total_amount_per_position' || sortField === 'sponsorship_cost') {
        aValue = Number(aValue) || 0;
        bValue = Number(bValue) || 0;
      } else {
        aValue = String(aValue).toLowerCase();
        bValue = String(bValue).toLowerCase();
      }

      if (aValue < bValue) {
        return sortDirection === 'asc' ? -1 : 1;
      }
      if (aValue > bValue) {
        return sortDirection === 'asc' ? 1 : -1;
      }
      return 0;
    });
  }, [results, sortField, sortDirection]);

  const handleSortChange = (field: SortField, direction: SortDirection) => {
    setSortField(field);
    setSortDirection(direction);
    setCurrentPage(1);
  };

  const handleSearch = async (params: ScholarshipsByProgramSearchParams) => {
    setLoading(true);
    setResults([]);
    setError('');
    setCurrentPage(1);
    setLoadingProgress('');

    try {
      const allResults: ProgramScholarshipItem[] = [];
      let currentPage = 1;
      let hasMoreData = true;
      const pageSize = 100;

      while (hasMoreData) {
        setLoadingProgress(`Fetching...`);

        const queryParams = {
          year_from: params.startYear ?? 20,
          year_to: params.endYear ?? 2099,
          current: params.status.toLowerCase() === 'current'
            ? true
            : params.status.toLowerCase() === 'not_current'
              ? false
              : undefined,
          program_code: params.programCode || undefined,
          page: currentPage,
          page_size: pageSize,
        };

        const response = await fetchScholarshipsByProgram(queryParams);

        allResults.push(...response.items);

        const totalPages = Math.ceil(response.meta.total / pageSize);
        if (currentPage >= totalPages) {
          hasMoreData = false;
        } else {
          currentPage++;
        }
      }

      setTimeout(() => {
        setResults(allResults);
        setLoading(false);
        setLoadingProgress('');
      }, 300);
    } catch (err) {
      console.error('Error fetching scholarships by program:', err);
      setError('Failed to load data.');
      setResults([]);
      setLoading(false);
      setLoadingProgress('');
    }
  };

  const paginatedResults = sortedResults.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const chartData = results.reduce((acc, item) => {
    const existingProgram = acc.find(program => program.program === item.program_code);
    if (existingProgram) {
      existingProgram.sponsorshipCost += Number(item.sponsorship_cost || 0);
    } else {
      acc.push({
        program: item.program_code,
        sponsorshipCost: Number(item.sponsorship_cost || 0)
      });
    }
    return acc;
  }, [] as { program: string; sponsorshipCost: number }[]);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 dark:bg-black/80 backdrop-blur-sm p-2 sm:p-4 font-poppins text-xs sm:text-sm md:text-base"
      onClick={onClose}
    >
      <div
        className="w-full sm:max-w-3xl md:max-w-4xl lg:max-w-5xl bg-white dark:bg-slate-900 rounded-2xl shadow-2xl dark:shadow-blue-900 overflow-hidden animate-fade-in-up max-h-[90vh] overflow-y-auto relative border border-gray-200 dark:border-slate-800"
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 sm:px-6 py-4 sm:py-5 bg-white dark:bg-slate-900 text-gray-800 dark:text-cyan-200 flex justify-between items-center border-b border-gray-200 dark:border-slate-800 rounded-t-2xl shadow-sm text-xs sm:text-sm md:text-base">
          <h2 className="text-base sm:text-lg md:text-2xl font-extrabold tracking-tight break-words text-blue-700 dark:text-cyan-300">Scholarships by Program</h2>
          <button
            onClick={onClose}
            className="w-9 h-9 flex items-center justify-center rounded-full text-xl font-bold text-gray-500 dark:text-gray-300 hover:text-red-600 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900 transition focus:outline-none focus:ring-2 focus:ring-red-300 dark:focus:ring-red-800"
          >
            ×
          </button>
        </div>

        {/* Body */}
        <div className="p-3 sm:p-6 space-y-4 text-xs sm:text-sm md:text-base text-gray-800 dark:text-gray-100 bg-white dark:bg-slate-900">
          <SearchForm onSearch={handleSearch} />

          {/* Chart Toggle Button */}
          {results.length > 0 && (
            <div className="flex justify-center">
              <button
                onClick={() => setShowChart(!showChart)}
                className="px-4 py-2 bg-blue-600 dark:bg-cyan-600 hover:bg-blue-700 dark:hover:bg-cyan-700 text-white font-medium rounded-lg transition-colors duration-200 flex items-center gap-2"
              >
                {showChart ? (
                  <>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                    </svg>
                    Hide Chart
                  </>
                ) : (
                  <>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                    </svg>
                    Show Chart
                  </>
                )}
              </button>
            </div>
          )}

          {loading ? (
            <div className="text-center text-gray-400 dark:text-gray-500 animate-pulse py-8 text-base sm:text-lg">
              {loadingProgress || 'Loading results...'}
            </div>
          ) : (
            <>
              {results.length > 0 && showChart && <ScholarshipByProgramBarChart data={chartData} />}
              <ResultTable
                data={paginatedResults}
                sortField={sortField}
                sortDirection={sortDirection}
                onSortChange={handleSortChange}
              />
            </>
          )}

          {sortedResults.length > itemsPerPage && (
            <Pagination
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalCount={sortedResults.length}
              pageSize={itemsPerPage}
            />
          )}

          {error && (
            <div className="text-center text-red-600 dark:text-red-400 py-4">
              {error}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ScholarshipsByProgramModal;